package com.study.recorderbutton;

import java.util.ArrayList;
import java.util.List;

import com.study.recorderbutton.adapter.RecorderAdapter;
import com.study.recorderbutton.entities.Recorder;
import com.study.recorderbutton.manager.MediaManager;
import com.study.recorderbutton.view.AudioRecorderButton;
import com.study.recorderbutton.view.AudioRecorderButton.AudioFinishRecorderListener;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {
	private ListView mListView;
	private ArrayAdapter<Recorder> mAdapter;
	private List<Recorder> mDatas = new ArrayList<Recorder>();
	private AudioRecorderButton mAudioRecorderButton;
	private View mAnimView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		init();
		
		mAudioRecorderButton.setAudioFinishRecorderListener(new AudioFinishRecorderListener() {
			
			@Override
			public void onFinish(float seconds, String filePath) {
				
				Recorder recorder = new Recorder(seconds, filePath);
				mDatas.add(recorder);
				//更新数据
				mAdapter.notifyDataSetChanged();
				//设置listview显示位置
				mListView.setSelection(mDatas.size()-1);
			}
		});
		
		mAdapter = new RecorderAdapter(MainActivity.this, mDatas);
		mListView.setAdapter(mAdapter);
		
		//listview的item点击事件
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//播放动画
				if(mAnimView != null){
					mAnimView.setBackgroundResource(R.drawable.adj);
					mAnimView = null;
				}
				mAnimView = view.findViewById(R.id.id_recorder_anim);
				mAnimView.setBackgroundResource(R.drawable.paly_anim);
				AnimationDrawable anim = (AnimationDrawable) mAnimView.getBackground();
				anim.start();
				//播放音频
				MediaManager.playSound(mDatas.get(position).getFilePath(), new MediaPlayer.OnCompletionListener() {
					
					@Override
					public void onCompletion(MediaPlayer mp) {
						mAnimView.setBackgroundResource(R.drawable.adj);
					}
				});
			}
		});
	}
	
	/**
	 * 控件初始化
	 */
	private void init(){
		mListView = (ListView) findViewById(R.id.listview);
		mAudioRecorderButton = (AudioRecorderButton) findViewById(R.id.recorder_button);
	}

	@Override
	protected void onResume() {
		MediaManager.resume();
		super.onResume();
	}

	@Override
	protected void onPause() {
		MediaManager.pause();
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		MediaManager.release();
		super.onDestroy();
	}
	
	
}
